package mqtt

import (
	mqtt "github.com/alibabacloud-go/onsmqtt-20200420/client"
	"testkjcld.bhecard.com/gitlab/kit/esim/config"
	"testkjcld.bhecard.com/gitlab/kit/esim/log"
)

type DeviceCredent struct {
	client *MQTTClient

	logger log.Logger

	conf config.Config
}

type DeviceCredentOption func(*DeviceCredent)

/*一机一密接口方法集*/
func NewDeviceCred(options ...DeviceCredentOption) *DeviceCredent {
	p := &DeviceCredent{}

	for _, option := range options {
		option(p)
	}

	if p.conf == nil {
		p.conf = config.NewNullConfig()
	}

	if p.logger == nil {
		p.logger = log.NewLogger()
	}

	/*初始化客户端*/
	var cliOpt MQTTClientOptions
	p.client = newMQTTClient(
		cliOpt.WithLogger(p.logger),
		cliOpt.WithConf(p.conf))
	return p
}

type DeviceCredentOptions struct{}

func (d *DeviceCredentOptions) WithDeviceConf(conf config.Config) DeviceCredentOption {
	return func(p *DeviceCredent) {
		p.conf = conf
	}
}

func (d *DeviceCredentOptions) WithDeviceLogger(logger log.Logger) DeviceCredentOption {
	return func(p *DeviceCredent) {
		p.logger = logger
	}
}

/*申请一机一密*/
func (d *DeviceCredent) RegisterDevice(clientId string) (*mqtt.RegisterDeviceCredentialResponse, error) {
	request := &mqtt.RegisterDeviceCredentialRequest{}
	request.ClientId = &clientId
	request.InstanceId = &d.client.instanceId
	d.logger.Infof("ClientId=[%s]InstanceId=[%s]", *request.ClientId, *request.InstanceId)
	return d.client.mqttClient.RegisterDeviceCredential(request)
}

/*查询设备的访问凭证*/
func (d *DeviceCredent) GetDeviceCredential(clientId string) (*mqtt.GetDeviceCredentialResponse, error) {
	request := &mqtt.GetDeviceCredentialRequest{}
	request.ClientId = &clientId
	request.InstanceId = &d.client.instanceId
	return d.client.mqttClient.GetDeviceCredential(request)
}

/*注销设备的访问凭证*/
func (d *DeviceCredent) UnRegisterDeviceCredential(clientId string) (*mqtt.UnRegisterDeviceCredentialResponse, error) {
	request := &mqtt.UnRegisterDeviceCredentialRequest{}
	request.ClientId = &clientId
	request.InstanceId = &d.client.instanceId
	return d.client.mqttClient.UnRegisterDeviceCredential(request)
}

/*更新设备的访问凭证*/
func (d *DeviceCredent) RefreshDeviceCredential(clientId string) (*mqtt.RefreshDeviceCredentialResponse, error) {
	request := &mqtt.RefreshDeviceCredentialRequest{}
	request.ClientId = &clientId
	request.InstanceId = &d.client.instanceId
	return d.client.mqttClient.RefreshDeviceCredential(request)
}
